<template>
	<div class="attendance-list">
		<div style=" width: 100%;display: flex;justify-content: space-between;">
			<div style="display: flex">
				<el-date-picker v-model="selectDate" :type="dateType" placeholder="选择日期"
					@change="changeDate">
				</el-date-picker>
				<el-select v-model="dateType" style="width: 80px;" @change="changeType">
					<el-option value="year" label="年"></el-option>
					<el-option value="month" label="月"></el-option>
					<el-option value="date" label="日"></el-option>
				</el-select>
			</div>
			<!-- 条件查询 -->
			<div style="display: flex;">
				<el-input v-model="fromData.nickName" placeholder="按手机号或姓名搜索"
					@change="onSubmit" style="width: 200px;">
				</el-input>
				<el-select v-model="fromData.departmentId" clearable placeholder="请选择部门"
					@change="onSubmit" @clear="clearDepartmentId"
					style="margin-left: 10px; width: 200px;">
					<el-option v-for="item in departmentList" :key="item.value"
						:label="item.label" :value="item.value">
					</el-option>
				</el-select>
				<el-button @click="reset" style="margin-left: 10px;" v-debounce>
					重置
				</el-button>
				<el-button type="primary" @click="exportExcel"
					style="margin-left: 10px;" v-debounce>
					导出Excel
				</el-button>
			</div>
		</div>
		<div class="attendance-table">
			<el-table :data="tableData" v-loading="loading" border stripe
				style="width: 100%" height="100%">
				<el-table-column prop="i" label="序号" fixed="left" width="50"></el-table-column>
				<el-table-column prop="nickName" label="姓名" fit></el-table-column>
				<el-table-column prop="normalTotal" label="正常打卡" fit></el-table-column>
				<el-table-column prop="lateTotal" label="迟到" fit></el-table-column>
				<el-table-column prop="tardyTotal" label="早退" fit></el-table-column>
				<el-table-column prop="absenteeismTotal" label="旷工" fit></el-table-column>
				<el-table-column prop="leaveTotal" label="请假" fit></el-table-column>
				<el-table-column prop="workOutsideTotal" label="外勤" fit></el-table-column>
				<el-table-column prop="businessTripTotal" label="出差" fit></el-table-column>
				<el-table-column prop="attendanceDays" label="出勤天数" fit></el-table-column>
				<el-table-column label="操作" width="120" fixed="right">
					<template slot-scope="scope">
						<div style="display: flex">
							<el-button @click="details(scope.row)" type="text" size="mini">
								详情
							</el-button>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="fromData.currentPage" :page-sizes="[20, 50, 100]" :page-size="fromData.pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</div>
	</div>
</template>

<script>
	import employeeAttendanceApi from "../../api/employeeAttendance.js";
	import departmentApi from "../../api/departmentManage.js";
	import apiURL from "../../api/apiURL.js";
	export default {
		data() {
			return {
				fromData: {
					currentPage: 1,
					pageSize: 50,
					year: null,
					yearMonth: null,
					yearMonthDay: null,
					departmentId: null,
					nickName: null
				},
				total: 0,
				tableData: [],
				loading: false,
				departmentList: [],
				dateType: "month",
				selectDate: null,
				// 导出Excel
				showExcel: false,
				excelUrl: apiURL.EXCEL_DOWNLOAD_URL,
			}
		},
		created() {
			const currentYear = new Date().getFullYear();
			let currentMonth = new Date().getMonth() + 1;
			if (currentMonth < 10) {
				currentMonth = '0' + currentMonth;
			}
			this.fromData.yearMonth = `${currentYear}-${currentMonth}`;
			this.selectDate = this.fromData.yearMonth;
			this.getAttendanceList();
			this.selectDepartments();
		},
		destroyed() {
			localStorage.removeItem("userAttendance");
		},
		methods: {
			selectDepartments() {
				departmentApi.selectDepartments().then(res => {
					if (res.code === 200) {
						this.departmentList = res.data.map(item => {
							let data = {
								label: item.name,
								value: item.id
							}
							return data;
						})
					}
				})
			},
			getAttendanceList() {
				//console.log("提交数据==>", this.fromData)
				this.loading = true
				employeeAttendanceApi.getAttendanceList(this.fromData).then(res => {
					if (res.code === 200) {
						this.total = res.data.total
						this.tableData = res.data.attendanceVoList.map((item,index) =>{
							item.i = (this.fromData.currentPage - 1) * this.fromData.pageSize + index + 1;
							return item;
						})
						this.loading = false
					}
				})
			},
			details(item) {
				localStorage.setItem("userAttendance", JSON.stringify(item))
				this.$router.push({
					path: "/employeeAttendance/attendance"
				})
			},
			// pageSize变化
			handleSizeChange(pageSize) {
				this.fromData.pageSize = pageSize
				this.getAttendanceList()
			},
			// 页码变化
			handleCurrentChange(curPage) {
				this.fromData.currentPage = curPage
				this.getAttendanceList()
			},
			// 条件查询重置
			reset() {
				this.fromData = {
					currentPage: 1,
					pageSize: 50,
					year: null,
					yearMonth: null,
					yearMonthDay: null,
					departmentId: null,
					nickName: null
				}
				this.getAttendanceList()
			},
			// 条件查询提交
			onSubmit() {
				this.fromData.currentPage = 1
				this.fromData.pageSize = 50
				this.getAttendanceList()
			},
			clearDepartmentId() {
				this.fromData.departmentId = null
				this.fromData.currentPage = 1
				this.fromData.pageSize = 50
				this.getAttendanceList()
			},
			changeDate() {
				//console.log("选择的日期==>",this.selectDate)
				this.fromData.year = null;
				this.fromData.yearMonth = null;
				this.fromData.yearMonthDay = null;
				if (this.selectDate !== null) {
					const year = this.selectDate.getFullYear();
					const month = this.selectDate.getMonth() + 1; // 月份从 0 开始，需要加 1
					const day = this.selectDate.getDate();
					// 格式化月份和日期，确保始终是两位数
					const formattedMonth = month < 10 ? '0' + month : month;
					const formattedDay = day < 10 ? '0' + day : day;
					if (this.dateType === "year") {
						this.fromData.year = year;
					} else if (this.dateType === "month") {
						this.fromData.yearMonth = `${year}-${formattedMonth}`;
					} else {
						this.fromData.yearMonthDay = `${year}-${formattedMonth}-${formattedDay}`;
					}
				}
				this.onSubmit()
			},
			changeType(){
				this.selectDate = new Date();
				this.changeDate();
			},
			exportExcel() {
				const loading = this.$loading({
					lock: true,
					text: 'Loading',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				const data = {
					year: this.fromData.year,
					yearMonth: this.fromData.yearMonth,
					yearMonthDay: this.fromData.yearMonthDay,
					departmentId: this.fromData.departmentId,
				}
				employeeAttendanceApi.attendanceStatistics(data).then(res => {
					if (res.code === 200) {
						loading.close();
						// const filePath = this.excelUrl + res.data;
            const filePath = res.data;
            employeeAttendanceApi.exportExcel(filePath)
            .then(response => {
              console.log(response);
              const url = URL.createObjectURL(response);
              const a = document.createElement('a');
              a.href = url;
              a.download = '员工出勤表.xlsx';
              a.target = '_blank';
              document.body.appendChild(a);
              a.click();
              URL.revokeObjectURL(url);
              a.remove();
            })
						// console.log("filePath=>",filePath)
						// const link = document.createElement('a');
            // link.target = '_blank';
						// link.href = filePath;
						// link.id = 'download-link';
						// link.click();
						// var element = document.getElementById('download-link');
						// if (element) {
						// 	document.body.removeChild(element); // 移除指定的 a 标签
						// }
						this.showExcel = false;
					}
				})
			}
		}
	}
</script>

<style>
	.attendance-list {
		height: 100%;
	}

	.attendance-table {
		height: 94%;
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		justify-content: center;
		margin-top: 10px;
	}
</style>
